<template>
  <div
    class="document-list-detail"
    :style="{height: height}"
    v-if="detailShow"
    v-loading.fullscreen.lock="loading"
    
  >
    <div class="document-detail-box" v-if="detail && detail.title">
      <!-- 详情头部 -->
      <div class="detail-top">
        <div class="detail-top-left">
          <div class="author">
            <span class="task-pointer" v-user="detail.createUser">
              <img class="author-img" :src="detail.createUserHead" v-if="detail.createUserHead"/>
              <img class="author-img" :src="avatarImage" v-else />
            </span>
            <div class="author-info">
              <p class="name">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="detail.createUserStaffId"></open-data>
                </template>
                <template v-else>
                  {{detail.createUserName}}
                </template>
              </p>
              <p class="time">{{detail.createTime | fmt_datehour}}</p>
            </div>
          </div>

          <div class="detail-attrs">
            <div class="detail-attrs-each outsideStatus">
              <!-- icon-unie65b -->
              <i
                class="iconfont"
                :class="{
                  'icon-neibu': !detail.allowShare,
                  'icon-unlock': detail.allowShare
              }"></i>
              <span v-if="detail.allowShare">{{$t('common.base.outside')}}<b>{{$t('wiki.detail.des1')}}</b></span>
              <span v-else>{{$t('common.base.inside')}}<b>{{$t('wiki.detail.des2')}}</b></span>
            </div>
            <div class="detail-attrs-each" v-if="detail.relationInfo && detail.relationInfo[0]">
              <span v-if="detail.relationInfo[0].taskId">{{$t('wiki.detail.label5')}}：<span class="link" @click="toOriginDetail('task')">{{ detail.relationInfo[0].taskNo || '' }}</span></span>
            </div>
            
            <div class="detail-attrs-each detail-attrs-catalog">
              {{$t('wiki.detail.label2')}}：
              <el-tooltip class="item" effect="dark" :content="detail.type" placement="bottom">
                <span class="detail-attrs-catalog-main">{{ detail.type }}</span>
              </el-tooltip>
            </div>
            
            <div class="detail-attrs-each detail-attrs-no">
              {{ $t('common.label.serialNumber') }}：{{ detail.wikiNumber }}
            </div>
            <div class="detail-attrs-each draftBox" v-if="!isReview">
              {{$t('wiki.detail.label1')}}：
              <el-popover
                placement="bottom"
                width="200"
                trigger="hover"
                popper-class="more-approve"
                :content="formatApprovers()"
                :disabled="detail.wikiApproveUsers && detail.wikiApproveUsers.length == 1">
              <span class="detail-status status1 approvers"  slot="reference" v-if="detail.examineState == 1 && detail.wikiApproveUsers && detail.wikiApproveUsers.length > 0"> 
                
                <template v-if="isOpenData && detail.wikiApproveUsers[0].staffId">
                  {{$t('common.wiki.await')}}<open-data type='userName' :openid="detail.wikiApproveUsers[0].staffId"></open-data> <span>{{detail.wikiApproveUsers[0].length > 1? $t('common.wiki.wait', {total: detail.wikiApproveUsers.length}) :$t('common.base.approve')}}</span>
                </template>
                <template v-else>
                  <template v-if="detail.wikiApproveUsers.length > 1">
                      {{$t('common.wiki.approver',{name: detail.wikiApproveUsers[0].displayName, total: detail.wikiApproveUsers.length})}}
                  </template>
                  <template v-else>
                    {{$t('common.wiki.await')}}{{ detail.wikiApproveUsers[0].displayName }}{{$t('common.base.approve')}}
                  </template>
                </template>
              </span>
            </el-popover>
              <span
                class="detail-status"
                :class="{
                  'status1': detail.examineState == 1,
                  'status2': detail.examineState == 2
                }"
                :type="detail.examineState == 1 ? '' : 'danger'"
                v-if="detail.examineState !== 1">
                {{[$t('wiki.detail.state1'), $t('wiki.detail.state2'), $t('wiki.detail.state3')][detail.examineState] || $t('wiki.detail.state4')}}
              </span>
            </div>
            
            <!-- 故障库Start -->
            <template>
             <div class="detail-attrs-each detail-attrs-catalog">
              {{$t('wiki.detail.label3')}}：
              <span v-if="detail.repairCostBegin || detail.repairCostEnd">{{ detail.repairCostBegin }} <span v-if="detail.repairCostBegin && detail.repairCostEnd">~</span> {{ detail.repairCostEnd }}</span>
            </div>
             <div class="detail-attrs-each detail-attrs-catalog">
              {{$t('wiki.detail.label4')}}：
              <span style="white-space: break-spaces;">{{ detail.productTypeList && detail.productTypeList.map(item=>item.hierarchyName).join(',') }}</span>
            </div>
            </template>
            <!-- 故障库End -->
          </div>
        </div>

        <div class="detail-top-right operating">
          <div class="check-btns">
            <el-button
              type="primary"
              @click="approve"
              v-if="showDetailApprove && detail.examineState == 1">
              {{$t('common.base.approve')}}
            </el-button>
            <!-- // 2021/9/9，转交不需要了，相关代码暂时注释，后续视情况删除 -->
            <!-- <el-button
              type="plain-third"
              @click="openTransferDialog"
              v-if="detail.examineState == 1 && (showDetailApprove || revokeShow)">
              转交
            </el-button> -->
            <el-button
              type="plain-third"
              @click="revoke"
              v-if="detail.examineState == 1 && revokeShow">
              {{$t('common.base.withdraw')}}
            </el-button>
          </div>
          <div style="display: inline-block">
            <span class="management" v-if="!isReview && detail.examineState != 1">
              <el-tooltip effect="dark" :content="$t('common.base.edit')" placement="bottom">
                <span
                  v-if="canEdit"
                  class="header-right-icon-each">
                  <i
                    class="iconfont icon-edit-square1"
                    @click="editArticle()">
                  </i>
                </span>
              </el-tooltip>
              <!-- <span
                class="header-right-icon-each"
                v-if="!detail.isDraft && allowEdit"
              >
                <el-dropdown v-if="!detail.allowShare" @command="command => inlineShare(command)">
                  <i class="iconfont icon-share1 icon-article-share"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="dept">部门</el-dropdown-item>
                    <el-dropdown-item command="person">人员</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <i
                  v-else
                  @click="shareDocument();trackEventHandler('share')"
                  class="iconfont icon-share1 icon-article-share">
                </i>
              </span> -->
              <el-tooltip effect="dark" :content="$t('common.base.share')" placement="bottom">
                <span
                  class="header-right-icon-each"
                  v-if="!detail.isDraft && shareEnable"
                >
                  <i
                    @click="wikiShare(detail);trackEventHandler('share')"
                    class="iconfont icon-share1 icon-article-share">
                  </i>
                </span>
              </el-tooltip>

              <!-- <el-tooltip effect="dark" :content="detail.circleState == 1 ? '取消发布' : '发布到自助门户'" placement="bottom">
                <span
                  class="header-right-icon-each"
                  v-if="!detail.isDraft && allowEdit && linkControl && isShowSelfServicePortal"
                  @click="changeRelease();trackEventHandler('share')"
                >
                  <i
                    class="iconfont icon-quanzi icon-article-share"
                    :class="{
                      'active': detail.circleState == 1
                    }">
                  </i>
                </span>
              </el-tooltip> -->
              <el-popover
                placement="top"
                v-model="moreListPopoverVisible"
                popper-class="more-list-popover"
                width="124">
                <div class="more-list">
                  <div v-if="allowCreate" class="more-item" @click="copyArticle()">{{$t('common.base.copy')}}</div>
                  <div v-if="detail.examineState === null" class="more-item" @click="moreListPopoverVisible = false;moveCatalogVisible = true">{{$t('wiki.list.btn.moveTo')}}</div>
                  <div v-if="allowDelete" class="more-item" @click="deleteArticle();trackEventHandler('detele')">{{$t('common.base.delete')}}</div>
                  <div class="more-item" @click="logDrawerShow = true;moreListPopoverVisible = false">{{$t('wiki.component.updateLog.title1')}}</div>
                  <div v-if="isList" class="more-item" @click="openFrame();trackEventHandler('open')">{{$t('common.base.openInNewPage')}}</div>
                </div>
                <i class="iconfont icon-ellipsis" slot="reference" v-if="detail.examineState !== 1"></i>
              </el-popover>
            </span>
          </div>
        </div>
      </div>

      <!-- 文章详情 -->
      <div class="detail-content">
        <div class="info">
          <div class="title">
            <span class="title-main">{{detail.title}}</span>
            <div class="title-label" v-if="detail.label && detail.label.length > 0">
              <span
                :key="index"
                v-for="(tag, index) in detail.label">
                {{ tag }}
              </span>
            </div>
          </div>
          <!-- 故障库Start -->
          <div v-if="isFault" class="Fault">
            <div class="FaultList"><label>{{$t('wiki.detail.label6')}}：</label><span>{{ detail.faultPerformance }}</span></div>
            <div class="FaultList"><label>{{$t('wiki.detail.label7')}}：</label><span>{{ detail.faultReason }}</span></div>
            <div class="FaultList">
              <label>{{$t('wiki.detail.label8')}}：</label>
              <span
                v-html="detail.content"
                class="wiki-content"
                @click="wikiClick($event)">
              </span>
            </div>
          </div>
          <!-- 故障库End -->
          <div v-else class="ql-container ql-snow content" :class="fontClass" style="border:none">
            <div class="ql-editor">
              <div
                v-html="detail.content"
                class="wiki-content"
                @click="wikiClick($event)">
              </div>
            </div>
          </div>
        </div>
        <!-- 详情页脚部分 -->
        <div
          class="footer"
          v-if="detail.attachment && detail.attachment.length > 0"
        >
          <div class="annex" v-if="detail.attachment && detail.attachment.length > 0">
            <span class="annex-left">{{$t('common.base.attachment')}}：</span>
            <div class="annex-right">
              <div class="base-comment-attachment base-file__preview">
                <base-file-item
                  v-for="file in detail.attachment"
                  :source="detail.attachment"
                  :key="file.id"
                  :file="file"
                  :fileDownloadAuth="wikiDownloadAuth"
                  size="small"
                ></base-file-item>
              </div>
            </div>
          </div>
        </div>
        <div class="status-view" v-if="detail.examineState === null">
          <span
            class="status-view-each canClick"
            @click="wikiStateData.isLike ? wikiCancelLike() : wikiLike()">
            <i
              class="iconfont"
              :class="{
                'icon-dianzan': !wikiStateData.isLike,
                'icon-like-fill': !!wikiStateData.isLike
            }"></i>
            <b>{{ wikiCountData.likeTimes || 0 }}</b>
          </span>
          <span
            class="status-view-each canClick">
            <i class="iconfont icon-pinglun"></i>
            <b>{{ wikiCountData.commentTimes || 0 }}</b>
          </span>
          <span
            class="status-view-each canClick"
            @click="wikiStateData.isCollection ? cancelCollection() : addCollection()">
            <i
              class="iconfont"
              :class="{
                'icon-shoucang': !wikiStateData.isCollection,
                'icon-yishoucang': !!wikiStateData.isCollection
            }"></i>
            <b>{{ wikiCountData.collectionTimes || 0 }}</b>
          </span>
          <span
            class="status-view-each">
            <i class="iconfont icon-yuedu"></i>
            <b>{{ wikiCountData.readTimes || 0 }}</b>
          </span>
        </div>
      </div>

      <approve-dialog :approve-data="approveData" ref="approveDialog" />

      <el-drawer
        :title="$t('common.base.updateLog')"
        size="280"
        :visible.sync="logDrawerShow">
        <update-log class="view-right" :wiki-id="wikiId" :no-header="true"></update-log>
      </el-drawer>
      <!-- start 转交弹窗 -->
      <!-- <base-modal title="转交办理" :show.sync="transferDialog.visible" width="600px" class="transfer-approve-dialog">
        <div class="base-modal-content">
          <div class="tips">审批转交适用于当前审批人无法对该事项做审批时，转交给上级领导进行审批的场景</div>
          <form-user
            :field="{ displayName: '转交人' }"
            placeholder="请选择新的审批人"
            v-model="transferDialog.approver"
            :see-all-org="true"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="transferDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="transferApprove" :disabled="transferDialog.pending">确 定</el-button>
        </div>
      </base-modal> -->
      <!-- end 转交弹窗 -->
    </div>
    <comment-box
      v-if="detail.examineState === null && commentShow"
      :wiki-id="detail.id"
      @commentChange="getWikiData()"
      :init-data="initData"
      :title="detail.title">
    </comment-box>
    <recommend-box
      v-if="detail.examineState === null && recommendShow"
      :font-class="fontClass"
      :labels="detail.label"
      :wiki-id="detail.id">
    </recommend-box>
    <move-catalog
      type="wiki"
      v-model="moveCatalogVisible"
      v-if="moveCatalogVisible"
      @moveEnd="getDocumnetDetail()"
      :beMoveData="detail"
      :getDataFromParent="true"
      :moveTreeDataFromProp="isFault?FaultLibrary:Library"
      >
    </move-catalog>

    <!-- 分享 -->
    <document-share
      ref="documentShare"
      :wiki-list="wikiListForShare">
    </document-share>
  </div>
  <div v-else class="document-list-detail empty">
    <div>
      <img class="empty-img" :src="noDataImage" />
    </div>
    <span class="empty-msg">{{deleteMsg || $t('common.base.tip.noData')}}</span>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import * as RepositoryApi from '@src/api/Repository';
import { formatDate } from 'pub-bbx-utils'

import ApproveDialog from './component/ApproveDialog.vue';

import { isShowSelfServicePortal } from '@shb-lib/version'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'

import { openTabForTaskView, openTabForWikiCreate } from '@src/util/business/openTab'

import UpdateLog from '../components/UpdateLog.vue'

import recommendBox from './component/recommendBox'
import commentBox from './component/comment'
import moveCatalog from '@src/modules/repository/document/components/moveCatalog'
import documentShare from '@src/modules/repository/document/components/documentShare'
import { getRootWindow } from '@src/util/dom'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'
import { getOssUrl } from '@src/util/assets'

/* api */
import { syncWiki, deleteWiki } from '@src/api/LLMApi'
import * as settingApi from '@src/api/SettingApi'

import { getRootWindowInitData } from '@src/util/window'
const rootWindowInitData = getRootWindowInitData()

const noDataImage = getOssUrl('/no_data.png')
const avatarImage = getOssUrl('/avatar.png')

export default {
  name: 'document-detail',
  mixins: [ThemeMixin],
  props: {
    info: {
      type: Object,
      default: () => ({}),
    },
    initData: {
      type: Object,
      default: () => ({}),
    },
    infoEdit: {
      type: Object,
      default: () => ({}),
    },
    isList: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    [ApproveDialog.name]: ApproveDialog,
    [UpdateLog.name]: UpdateLog,
    [recommendBox.name]: recommendBox,
    [commentBox.name]: commentBox,
    [moveCatalog.name]: moveCatalog,
    [documentShare.name]: documentShare,
  },
  data() {
    return {
      avatarImage,
      noDataImage,
      isOpenData,
      allowEdit: false,
      allowDelete: false,
      form: this.buildForm(), // 附件存储格式
      wikiId: '', // 通知公告id
      showDetailApprove: false,
      approveData: {},
      isReview: false,
      refuseInfo: {
        text: '',
      },
      show: false,
      rules: {
        text: [
          {
            required: true,
            message: i18n.t('wiki.detail.tips1'),
            trigger: 'blur',
          },
        ],
      },
      detail: {}, // 文章详情
      loading: false,
      deleteMsg: null,
      revokeShow: false,
      url: '',
      detailShow: true,

      logDrawerShow: false,

      // transferDialog: { // 审批转交弹窗
      //   visible: false,
      //   pending: false,
      //   approver: {}
      // },
      count: {
        good: 1,
        comment: 2,
        favorite: 3,
        watch: 4
      },
      checkGood: true,
      checkFavorite: true,

      operationAuth: {},
      wikiCountData: {},
      wikiStateData: {},

      moreListPopoverVisible: false,

      likeLoading: false,
      collectionLoading: false,

      moveCatalogVisible: false,
      canEdit: false,

      wikiListForShare: [],
      shareEnable: false, // 是否有分享权限
      // 故障库
      FaultLibrary:[],
      Library:[],
      wikiApproveUsers: [],
      wikiDownloadAuth: true, // 是否允许下载附件内容

    };
  },
  async mounted() {
    this.shareEnable = await this.getWikiConfig(); // 获取知识库配置
    this.getId();
    this.showButton()
    this.addBrowseRecord()
    this.fetchWikiAuthConfig()
  },
  methods: {
    /**格式化人员 */
    formatApprovers () {
      return (this.detail.wikiApproveUsers || []).map(obj => obj.displayName).join('，');
    },
    wikiClick(e) {
      if(/^img$/i.test(e.target.nodeName)) {
        const img = e.target.currentSrc
        this.$previewElementImg(img, [img]);
      }
    },
    /** 获取是否允许下载附件内容的配置 */
    async fetchWikiAuthConfig() {
      try {
        const WIKI_DOWNLOAD_CODE = 'wikiDownloadAuth'
        const { data = [], success, message } = await settingApi.getTenantConfigByCodeList({ codeList: [WIKI_DOWNLOAD_CODE] })
        if(!success) return this.$message.warning(message)
        if(data.length) {
          this.wikiDownloadAuth = !!data.find(item=> item.configCode === WIKI_DOWNLOAD_CODE)?.isOpen;
        }
      } catch(err) {
        console.error('[getTenantConfigByCodeList error]', err)
      }
    },
    async getWikiConfig() {
      try {
        let res = await RepositoryApi.getWikiConfig()
        return res?.result?.permitShare || false;
      } catch (e) {
        console.error(e)
        return false;
      }
    },
    async wikiShare (wiki) {
      // 点击分享的时候需要判断是否有分享权限
      let share = await this.getWikiConfig();
      if(!share) {
        this.$message.error(this.$t('wiki.detail.tips2'))
        return
      }
      this.wikiListForShare = [wiki];
      let show = this.wikiListForShare.every(v => v.allowShare === 1);
      (this.$refs.documentShare || {}).shareDocument(show)
    },
    buildForm() {
      return {
        content: '',
        attachments: [],
        showInOwn: 0,
      };
    },

    getId() {
      if (window.location.href.indexOf('?') != -1) {
        let array = window.location.href.split('?')[1].split('&');
        let params = [];
        array.forEach((item) => {
          params.push({ name: item.split('=')[0], value: item.split('=')[1] });
        });

        let shenpi = false;
        params.forEach((item) => {
          if (item.name == 'wikiId') {
            this.wikiId = item.value;
          }
          if (item.name == 'objId') {
            this.wikiId = item.value;
          }
          if (item.name == 'id') {
            this.wikiId = item.value;
          }
          if (item.name == 'action' && item.value == 'approve') {
            this.isReview = true;
          }
          if (item.name == 'from' && item.value == 'approve') {
            shenpi = true;
          }
        });
        if (
          !shenpi
          && !this.initData.userInfo.authorities.INFO_VIEW
          && !this.initData.userInfo.authorities.INFO_COMPILER
          && !this.initData.userInfo.authorities.VIP_INFO_CREATE
        ) {
          this.deleteMsg = this.$t('wiki.detail.tips3');
          this.detailShow = false;
          return;
        }
        this.getDocumnetDetail();
        // this.getFileOperationAuth()
      }
    },

    async getApproveDetail() {
      try {
        let params = {
          objId: this.info.id ? this.info.id : this.wikiId ? this.wikiId : null,
        };
        let res = await RepositoryApi.getApprove(params);

        if (res.success) {
          this.approveData = res.result;
          this.approveData.createTime = formatDate(this.approveData.createTime)
          this.approveData.approvers.forEach((item) => {
            if (item.userId == this.initData.userInfo.userId)
              this.showDetailApprove = true;
          });
          this.approveData.isList = this.isList;
          if (this.detail.originalId) {
            this.approveData.wikiId = this.detail.originalId;
          }
          if (this.approveData.proposer == this.initData.userInfo.userId) {
            this.revokeShow = true;
          }
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      } catch (err) {
        console.error(err);
      }
    },

    // 获取文档库详情
    async getDocumnetDetail() {
      try {
        let params = {
          wikiId: this.info.id
            ? this.info.id
            : this.wikiId
              ? this.wikiId
              : null,
          updateReadTimes: true,
        };
        this.detailShow = true;
        if (!params.wikiId) {
          this.detail = null;
          this.detailShow = false;
          return;
        }
        this.loading = true;
        let res = await RepositoryApi.getInlineDetail(params);
        this.loading = false;

        if (res.success) {
          // TODO-bdz 中文判断
          if (res.message == '已删除') {
            this.detail = null;
            this.deleteMsg = this.$t('wiki.detail.tips4');
            this.detailShow = false;
          } else {
            this.getWikiData()
            this.detail = res.result;

            // 根据知识库类型，获取对应的目录菜单
            if(this.detail.wikiType === 1){
              this.getFaultTypes()
            }else{
               this.getTypes()
            }

            let authorities = this.initData.userInfo.authorities
            if (authorities.INFO_COMPILER || authorities.INFO_DELETE) {
              this.allowEdit = !!authorities.INFO_COMPILER;
              this.allowDelete = !!authorities.INFO_DELETE;
            } else {
              if (
                this.detail.createUser == this.initData.userInfo.userId
                && authorities.VIP_INFO_CREATE
              ) {
                this.allowEdit = true;
                this.allowDelete = true
              } else {
                this.allowEdit = false;
                this.allowDelete = false
              }
            }
            if (this.isReview) {
              this.getApproveDetail();
              this.approve();
              return;
            }
            if (this.detail.examineState && this.detail.examineState == 1) {
              this.getApproveDetail();
            }
          }
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      } catch (err) {
        console.error(err);
        this.loading = false;
      } finally {
        this.$platform.setTabTitle({
          id: window.frameElement.dataset.id,
          title: this.detail?.title || this.$t('wiki.detail.wikiDetail'),
        })
      }
    },

    // 新页面打开通知公告详情
    openFrame() {
      this.moreListPopoverVisible = false
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `document_detail_${this.detail.id}`,
      //   title: '知识库列表',
      //   url: `/wiki/detail/page?wikiId=${this.detail.id}`,
      //   reload: true,
      //   close: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageWikiDetail,
        key: this.detail.id,
        params: `wikiId=${this.detail.id}`,
        reload: true,
        fromId
      })
    },

    // 编辑文章操作，查询详情接口，有人正在编辑提示不跳转
    async editArticle() {
      try {
        let params = {
          wikiId: this.info.id
            ? this.info.id
            : this.wikiId
              ? this.wikiId
              : null,
          updateReadTimes: false,
        };
        let res = await RepositoryApi.getInlineDetail(params);

        if (res.success) {
          let detail = res.result;

          if (detail.isLock && detail.examineState != 1) {
            this.$platform.notification({
              title: this.$t('wiki.detail.title1'),
              type: 'error',
            });
          } else {
            let fromId = window.frameElement.getAttribute('id');

            // this.$platform.openTab({
            //   id: `wiki_create_${params.wikiId}`,
            //   title: '知识库编辑',
            //   url: `/wiki/edit/page?wikiId=${params.wikiId}`,
            //   reload: true,
            //   close: true,
            //   fromId,
            // });
            openAccurateTab({
              type: PageRoutesTypeEnum.PageWikiEdit,
              key: params.wikiId,
              params: `wikiId=${params.wikiId}&wikiType=${this.detail.wikiType}`,
              reload: true,
              fromId
            })
          }
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      } catch (err) {
        console.error(err);
      }
    },
    deleteLLMWiki(ids) {
      
      const params = {
        ids,
        tenantId: rootWindowInitData?.user?.tenantId,
      }
      
      deleteWiki(params).then((result) => {
      })
      
    },
    // 删除文章
    async deleteArticle() {
      this.moreListPopoverVisible = false
      try {
        if (!(await this.$platform.confirm(this.$t('common.base.tip.areYouSureYouWantDeletIt')))) return;

        let params = {
          wikiIds: [this.detail.id],
        };

        let res = await RepositoryApi.deleteDocument(params);

        if (res.success) {
          
          this.deleteLLMWiki(params.wikiIds)
          
          this.$platform.notification({
            title: '文章已删除成功。',
            type: 'success',
          });

          if (!this.isList) {
            let id = window.frameElement.dataset.id;
            this.$platform.closeTab(id);

            let fromId = window.frameElement.getAttribute('id');
            // this.$platform.openTab({
            //   id: 'M_INFO_DOC',
            //   title: '知识库列表',
            //   url: '/wiki',
            //   reload: true,
            //   close: true,
            //   fromId,
            // });
            openAccurateTab({
              type: PageRoutesTypeEnum.PageWikiList,
              reload: true,
              fromId
            })
          } else {
            if (this.info.isLast) {
              this.$parent.resetPageNum();
            } else {
              this.$emit('search');
            }
          }
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      } catch (e) {
        console.error(e);
      }
    },

    search() {
      this.$emit('search');
    },

    approve() {
      this.$refs.approveDialog.open();
    },

    async revoke() {
      try {
        if (!(await this.$platform.confirm(this.$t('common.base.tip.areYouSureYouWantWithdrawIt')))) return;

        let params = {
          id: this.approveData.id,
        };

        let res = await RepositoryApi.revoke(params);

        if (res.success) {
          if (!this.isList) {
            window.location.reload();
          } else {
            this.$emit('search');
          }
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      } catch (e) {
        console.error(e);
      }
    },

    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'delete') {
        window.TDAPP.onEvent('pc：知识库详情-删除事件');
        return;
      }
      if (type === 'share') {
        window.TDAPP.onEvent('pc：知识库详情-分享事件');
        return;
      }
      if (type === 'open') {
        window.TDAPP.onEvent('pc：知识库详情-新页面打开');
        return;
      }
    },
    changeRelease() {
      this.$confirm(
        this.detail.circleState == 1 ? this.$t('wiki.detail.des3') : this.$t('wiki.detail.des4'),
        this.$t('common.base.toast'),
        {
          confirmButtonText: this.$t('common.base.confirm'),
        }
      )
        .then(() => {
          RepositoryApi.releaseCircle({
            id: this.detail.id,
            circleState: 1 - this.detail.circleState * 1,
          }).then((res) => {
            if (res.code == 0) {
              this.detail.circleState = 1 - this.detail.circleState * 1;
              this.$message({
                message: this.detail.circleState == 1 ? this.$t('wiki.detail.des5') : this.$t('common.base.tip.cancelSuccess'),
                duration: 1500,
                type: 'success',
              });
              this.$emit('releaseCircle', {
                id: this.detail.id,
                circleState: this.detail.circleState * 1,
              });
              let fromId = window.frameElement.getAttribute('fromid') || '';
              if (!fromId) return;
              this.$platform.refreshTab(fromId);
            } else {
              this.$message({
                message: res.message,
                duration: 1500,
                type: 'error',
              });
            }
          });
        })
        .catch(() => {});
    },
    toOriginDetail(type) {
      if (type === 'task') {
        let {taskId, taskNo} = (this.detail.relationInfo?.[0] || {})
        openTabForTaskView(taskId, void 0, void 0, void 0, taskNo)
      }
    },
    copyArticle() {
      openTabForWikiCreate({copyId: this.currWikiId})
    },

    addCollection() {
      if(this.collectionLoading) return
      this.collectionLoading = true
      RepositoryApi.addCollection({
        wikiId: this.currWikiId
      }).then(res => {
        if(res.code === 0) {
          this.$platform.notification({
            title: this.$t('wiki.detail.tips5'),
            type: 'success'
          })
          this.getWikiData()
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      }).finally(() => {
        this.collectionLoading = false
      })
    },

    cancelCollection() {
      if(this.collectionLoading) return
      this.collectionLoading = true
      RepositoryApi.cancelCollection({
        wikiId: this.currWikiId
      }).then(res => {
        if(res.code === 0) {
          this.$platform.notification({
            title: this.$t('wiki.detail.tips6'),
            type: 'success'
          })
          this.getWikiData()
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      }).finally(() => {
        this.collectionLoading = false
      })
    },

    wikiLike() {
      if(this.likeLoading) return
      this.likeLoading = true
      RepositoryApi.wikiLike({
        wikiId: this.currWikiId
      }).then(res => {
        if(res.code === 0) {
          this.$platform.notification({
            title: this.$t('wiki.detail.tips7'),
            type: 'success'
          })
          this.getWikiData()
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      }).finally(() => {
        this.likeLoading = false
      })
    },

    wikiCancelLike() {
      if(this.likeLoading) return
      this.likeLoading = true
      RepositoryApi.wikiCancelLike({
        wikiId: this.currWikiId
      }).then(res => {
        if(res.code === 0) {
          this.$platform.notification({
            title: this.$t('wiki.detail.tips8'),
            type: 'success'
          })
          this.getWikiData()
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      }).finally(() => {
        this.likeLoading = false
      })
    },

    getWikiData() {
      RepositoryApi.getWikiData({
        id: this.currWikiId
      }).then(res => {
        if(res.code === 0) {
          this.wikiCountData = res.result?.times || {}
          this.wikiStateData = res.result?.state || {}
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      })
    },

    getFileOperationAuth() {
      RepositoryApi.getFileOperationAuth({
        id: this.currWikiId
      }).then(res => {
        if (res.code === 0) {
          this.operationAuth = res.result || {}
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
      }).catch(err => {
        console.log(err)
      })
    },
    showButton() {
      RepositoryApi.showButton({
        wikiId: this.currWikiId
      }).then(res => {
        if (res.code === 0) {
          this.canEdit = res.result
        }
      }).catch(err => {
        console.err(err)
      })
    },

    // 增加个人浏览记录
    addBrowseRecord() {
      RepositoryApi.addBrowseRecord({
        wikiId: this.currWikiId
      }).catch(err => {
        console.err(err)
      })
    },

    // 获取知识空间分类二级树状结构
    async getTypes () {
       let res = await RepositoryApi.getDocumentTypes();
        if(res.success) {
          this.Library = res.result
        }
    },
    // 获取故障库分类二级树状结构
    async getFaultTypes () {
       let res = await RepositoryApi.getDocumentTypes({
        type:1
       });
        if(res.success) {
          this.FaultLibrary = res.result
        }
    }
  },
  computed: {
    // 当前选择的是否是故障库
    isFault(){
      return this.detail.wikiType === 1
    },
    allowCreate() {
      return this.initData?.userInfo.authorities.VIP_INFO_CREATE
    },
    height() {
      return this.isList ? '100%' : '100vh';
    },

    // padding() {
    //   return this.isList ? "0 50px" : "0 100px";
    // },

    fontClass() {
      return document.body.clientWidth > 1800 ? 'font-class' : '';
    },

    // 联客商城灰度开关
    linkControl() {
      // return this.initData.openLinkC;
      const RootWindow = getRootWindow(window);
      return this.initData.openLinkC || RootWindow.grayAuth?.portal || false;

    },
    isShowSelfServicePortal() {
      return isShowSelfServicePortal()
    },
    currWikiId() {
      return this.info.id
        ? this.info.id
        : this.wikiId
          ? this.wikiId
          : null
    },

    commentShow() {
      return this.initData?.wikiConfig?.comment
    },
    recommendShow() {
      return this.initData?.wikiConfig?.relevantRecommend
    },
    authorities() {
      return this.initData?.userInfo?.authorities || {}
    },
    allowEditInfo() {
      return this.authorities.VIP_INFO_EDIT
    }
  },
};
</script>

<style lang="scss">
.Fault{
  width: 100;
  .FaultList{
    margin-top: 8px;
    display: flex;
    label{
      flex:0 1 80px;
      min-width: 80px;
    }
  }
}
.document-list-detail {
  display: flex;
  flex-direction: column;
  overflow: auto;

  padding: 12px;
  background: transparent;

  .document-detail-box {
    background: #fff;
    border-radius: 4px;
  }

  .detail-top {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    min-height: 60px;
    // max-height: 120px;
    padding: 12px 16px;
    border-bottom: 1px solid #e8eff0;

    .author {
      font-size: 0;
      display: inline-block;
      border-right: 1px solid #E8E8E8;

      .author-img {
        vertical-align: middle;
        display: inline-block;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 8px;
      }

      .author-info {
        vertical-align: middle;
        display: inline-block;
        width: 146px;

        .name {
          font-size: 14px;
          margin-bottom: 0px;
          line-height: 24px;
          font-weight: 400;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        .time {
          font-size: 12px;
          margin: 0;
          font-weight: 400;
          color: #8C8C8C;
          line-height: 26px;
        }
      }
    }

    .operating {
      line-height: 40px;

      .published {
        display: inline-block;
      }

      .draftBox {
        display: inline-block;
        margin-right: 10px;
      }

      .icon-permission {
        font-size: 14px;
        color: #b0bcc3;
        margin-right: 3px;
      }

      .management {
        .icon-edit {
          display: inline-block;
          width: 25px;
          height: 25px;
          font-size: 14px;
          color: $color-primary-light-6;
        }

        .icon-delete {
          display: inline-block;
          width: 25px;
          height: 25px;
          font-size: 16px;
          color: $color-primary-light-6;
        }
      }

      .icon-operating {
        display: inline-block;
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        font-size: 16px;
        color: $color-primary-light-6;

        cursor: pointer;
      }

      .share {
        display: inline-block;

        width: 20px;
        height: 20px;
        line-height: 20px;

        cursor: pointer;

        .icon-article-share {
          font-size: 16px;
          color: $color-primary-light-6;
        }
      }

      .open {
        display: inline-block;
        height: 30px;
        line-height: 30px;
        margin-left: 10px;
        color: $color-primary-light-6;

        cursor: pointer;
      }

      .green-btn {
        background: #55b7b4;
        border: transparent;
        margin-left: 10px;
      }

      .white-btn {
        background: #fff;
        color: #333;
        border: 1px solid #e2e2e2;

        &:hover {
          @include borderColorPrimaryLight5();
          @include backgroundColorPrimaryLight1();
          color: #fff;
        }
      }
    }
  }
  .title-label {
    margin-left: 8px;
    display: inline;
    vertical-align: middle;
    span {
      background: $color-primary-light-1;
      border-radius: 4px;
      border: 1px solid $color-primary-light-1;
      height: 22px;
      line-height: 22px;
      font-size: 12px;
      font-weight: 400;
      color: $color-primary-light-6;
      display: inline-block;
      box-sizing: border-box;
      padding: 0 8px;
      margin-left: 4px;
      vertical-align: text-top;
    }
  }

  .detail-content {
    flex: 1;
    overflow: auto;
    padding: 0 100px 16px 100px;

    .info {
      .title {
        margin: 0;
        padding: 16px 0 13px;
        display: inline-block;
        font-size: 18px;
        font-weight: bold;
        color: #262626;
        line-height: 25px;
      }
      .title-main {
        display: inline-block;
        font-size: 18px;
        font-weight: bold;
        color: #262626;
        line-height: 25px;
        vertical-align: middle;
      }

      .content {
        padding-bottom: 16px;
        word-break: break-all;

        p > img {
          max-width: 100%;
        }

        // p {
        //   line-height: 28px;
        // }
      }

      .font-class {
        font-size: 16px !important;

        p {
          line-height: 30px;
        }
      }
    }

    .footer {
      padding: 12px;
      box-shadow: 0px 2px 8px 0px rgba(144, 171, 184, 0.5);
      border-radius: 4px;
      font-size: 0;
      margin-bottom: 50px;

      .tags {
        // display: inline-block;
        vertical-align: top;
        font-size: 0;
        padding-bottom: 10px;

        .icon-tags {
          vertical-align: middle;
          font-size: 16px;
          color: #b0bcc3;
        }

        .detail-tag {
          vertical-align: middle;
          max-width: 76px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;

          margin-left: 4px;
          border: none;
          background: #e8eff0;
          color: #606266;
        }
      }

      .dividing-line {
        // display: inline-block;
        height: 22px;
        width: 1px;
        background: #848e92;
        margin: 0 20px;
        vertical-align: top;
      }

      .annex {
        vertical-align: top;
        display: inline-block;
        font-size: 0;

        .annex-left {
          vertical-align: top;
          display: inline-block;
          font-size: 14px;
          line-height: 35px;
        }

        .annex-right {
          vertical-align: top;
          display: inline-block;

          .annex-item {
            font-size: 14px;
          }

          .base-file-info {
            white-space: inherit;
          }
        }
      }
    }
  }
}

.empty {
  text-align: center;
  padding-top: 100px;
  height: 100vh;
  background: #FFFFFF;

  .empty-img {
    width: 160px;
    height: 160px;
  }

  .empty-msg {
    display: block;
    padding-top: 8px;
    font-size: $font-size-base;
    color: $text-color-regular;
  }
}

.base-file-del {
  display: none;
}

.detail-attrs {
  display: flex;
  width: 550px;
  flex-wrap: wrap;
  margin-left: 24px;
  justify-content: space-between;
  &-each {
    // width: 49%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-size: 14px;
    line-height: 22px;
  }
  .approvers {
    cursor: pointer;
    .iconfont {
      color: #8c8c8c;
      &:hover{
        color: #595959;
      }
    }
  }
}
.link {
  color: $color-primary-light-6;
  cursor: pointer;
}

.ql-editor {
  padding: 0;
  .wiki-content {
    font-size: 14px;
    font-weight: 400;
    color: #262626;
    line-height: 26px;
    p {
      font-size: 14px;
      font-weight: 400;
      color: #262626;
      line-height: 26px;
    }
    img {
      cursor: pointer;
    }
  }
}
.detail-attrs-catalog {
  display: flex;
  &-main {
    direction: rtl;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.detail-top-left {
  display: flex;
}
.detail-top-right {
  display: flex;
}

.icon-quanzi.active {
  color: $color-primary-light-6;
}

.management {
  font-size: 0;
}
.header-right-icon-each {
  margin-right: 12px;
  .iconfont {
    font-size: 18px;
  }
  .iconfont:hover {
    color: $color-primary-light-6;
  }
  .iconfont:focus {
    color: $color-primary-light-6;
  }
}
.icon-ellipsis:hover {
  color: $color-primary-light-6;
}

.detail-status {
  font-size: 14px;
  font-weight: 400;
  line-height: 20px;
  color: #262626;
  &.status1 {
    color: #FF9200;
  }
  &.status2 {
    color: #FF4D4F;
  }
}

.status-view {
  &-each {
    color: #595959;
    margin-right: 24px;
    font-size: 0;
    line-height: 20px;
  }
  .canClick {
    cursor: pointer;
  }
  b {
    font-size: 14px;
    font-weight: 400;
    vertical-align: middle;
  }
  .iconfont {
    font-size: 16px;
    font-weight: 400;
    vertical-align: middle;
    &:before {
      margin-right: 4px;
    }
  }
  .icon-like-fill {
    color: #ff7043;
  }
  .icon-yishoucang {
    color: $color-primary-light-6;
  }
}
.more-item {
  font-size: 14px;
  font-weight: 400;
  color: #666666;
  line-height: 34px;
  cursor: pointer;
  padding: 0 20px;
}
.check-btns {
  font-size: 0;
}
.management .iconfont {
  cursor: pointer;
}


.detail-attrs-each {
  color: #595959;
  margin-right: 4px;
}
.outsideStatus {
  span > b {
    font-weight: normal;
    color: #8c8c8c;
    font-size: 12px;
  }
}
</style>
<style lang="scss" >
  .more-list-popover {
    padding: 0 0 10px;
    .iconfont {
      font-size: 18px;
    }
  }
  .more-approve {
    padding: 10px 12px;
  }
</style>